<template>
  <section>
      <el-tabs size="mini" :before-leave='leaveTab' v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="账号管理" name="0"></el-tab-pane>
        <el-tab-pane label="角色管理" name="1"></el-tab-pane>
        </el-tabs>
      <div class="filter-container">
            <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
        </div>
      <el-table max-height="500"
                :data="role_list"
                style="width: 100%">
            
            <el-table-column align="center" label="角色名称">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="创建时间">
                <template slot-scope="scope">
                    <span>{{scope.row.createTime}}</span>
                </template>
            </el-table-column> -->
            <el-table-column align="left" label="备注">
                <template slot-scope="scope">
                    <span>{{scope.row.note}}</span>
                </template>
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="100">
                <template slot-scope="scope">
                    <el-dropdown>
                        <el-button
                                type="text">
                            操作<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="800px" @close="dialogClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px">
                <el-form-item label="角色名称" prop="name">
                    <common-input v-model="form.name" placeholder="" />
                </el-form-item>
                <el-form-item label="备注" prop="note">
                    <common-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" placeholder="" maxlength="100" v-model="form.note" />
                </el-form-item>
                <el-form-item label="权限列表" prop="permissions">
                    <!-- <el-checkbox-group v-model="form.permissions"> -->
                        <template v-for="item in menu_list">
                            <el-card class="box-card" :key="item.id" style="margin-bottom:10px;">
                                <div slot="header" class="clearfix">
                                    <span>{{item.name}}</span>
                                </div>
                                <template v-for="item2 in item.children">
                                    <el-row :gutter="20" :key="item2.id">
                                        <el-col :span="6">
                                            {{ item2.name }}：
                                        </el-col>
                                        <el-col :span="18">
                                            <el-checkbox-group v-model="item2.permissions">
                                                <template v-for="item3 in item2.children">
                                                    <el-checkbox :key="item3.fullCode" :label="item3.fullCode">{{item3.name}}</el-checkbox>
                                                </template>
                                            </el-checkbox-group>
                                        </el-col>
                                    </el-row>

                                </template>
                            </el-card>

                        </template>
                    <!-- </el-checkbox-group> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="cancel('form')">取消</el-button>
                <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
                <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
            </div>
        </el-dialog>
  </section>
</template>

<script>
    import {
        isPassword
    } from '../../utils/validator'
    import {
        agency_role_list,
        agency_menus,
        agency_role_create,
        agency_role_detail,
        agency_role_edit,
        agency_role_delete
    } from '../../api/agency';
    import {
        next_no
    } from '../../api/sys';
export default {
    components: {
    },
  data() {
    return {
        agencyId: 0,
        activeName: '1',
        list: null,
        listLoading: true,
        listQuery: {
            page: 1,
            num: 20,
            keyword: undefined,
            status: '',
            password: undefined,
        },
        status_list: [
            {
                value: 1,
                label: '可用'
            },
            {
                value: 2,
                label: '不可用'
            }
        ],
        total: null,
        dialogStatus: '',
        dialogFormVisible: false,
        textMap: {
            update: '编辑角色',
            create: '新增角色'
        },
        form: {
            id: undefined,
            name: undefined,
            note: undefined,
            permissions: [],
        },
        rules: {
            name: [
                {
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }
            ],
        },
        role_list: [],
        menu_list: []
    }
  },
  mounted() {
  },
        created() {
            this.agencyId = parseInt(this.$route.query.id);
            this.getRoleList();
            this.getMenuList();
        },

  methods: {
      getRoleList() {
        agency_role_list(this.agencyId).then(res => {
            this.role_list = res.data
        })

      },
      getMenuList() {
        agency_menus().then(res => {
            this.menu_list = res.data
        })

      },
    handleCreate() {
        this.resetTemp();
        this.setPermissions();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
    },
    resetTemp() {
        this.form = {
            id: undefined,
            name: undefined,
            note: undefined,
            permissions: [],
        };
    },
    create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
            if (valid) {
                this.form.permissions = this.getPermissions()
                agency_role_create(this.agencyId, this.form)
                    .then(() => {
                        this.dialogFormVisible = false;
                        this.getRoleList();
                        this.$message.success("角色创建成功");
                    })
            } else {
                return false;
            }
        });
    },
    update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
            if (valid) {
                this.dialogFormVisible = false;
                this.form.permissions = this.getPermissions()
                agency_role_edit(this.agencyId, this.form.id, this.form).then(() => {
                    this.dialogFormVisible = false;
                    this.getRoleList();
                    this.$message.success("角色更新成功");
                });
            } else {
                return false;
            }
        });
    },
    cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
    },
    handleUpdate(row) {
        agency_role_detail(this.agencyId, row.id)
            .then(response => {
                this.form = response.data;
                this.setPermissions();
                this.dialogFormVisible = true;
                this.dialogStatus = 'update';
            });
    },
    handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                agency_role_delete(this.agencyId, row.id)
                    .then(() => {
                        this.$message.success("角色删除成功");

                        this.getRoleList();
                    });
            }).catch(()=>{});
    },
    dialogClose() {
        this.$refs.form.resetFields();
    },
    handleClick(tab, event) {
        if(this.activeName == "0") {
            //账号管理
            this.$router.push("/company/vendor_account?id=" + this.agencyId) 
        }
    },
    leaveTab(activeName, oldActiveName) {

    },
    getPermissions() {
        let permissions = [];
        this.menu_list.forEach((item)=>{
            item.children.forEach((item2)=>{
                // console.log(item2.permissions)
                if(item2.permissions && item2.permissions.length > 0) {
                    permissions = permissions.concat(item2.permissions)
                }
            })
        });

        return permissions;
    },
    setPermissions() {
        this.menu_list.forEach((item)=>{
            item.children.forEach((item2)=>{
                let p = [];
                item2.children.forEach((item3)=>{
                    let has = false;
                    if(this.form.permissions && this.form.permissions.length > 0) {
                        this.form.permissions.forEach((item4)=>{
                            if(item4 == item3.fullCode) {
                                has = true;
                                return false;
                            }
                        })
                    }

                    if(has) {
                        p.push(item3.fullCode)
                    }
                });

                item2.permissions = p;
                // console.log(p)
            })
        });

        console.log(this.menu_list);
    }
  }
};
</script>
